<template>
  <div>
    <ContentWrap>
      <div class="btnWrap routeHeader">
        <div>
          <el-button @click="saveData" type="primary" v-hasPermi="['order:technolReviewTbl:save']" :disabled="disabled">保存</el-button>
          <el-button @click="submitData" type="primary" v-hasPermi="['order:technolReviewTbl:submit']" :disabled="disabled">提交</el-button>
          <el-button @click="close">关闭</el-button>
        </div>
      </div>
      <div class="btnWrap">
        <el-button @click="addRow" type="primary" v-if="route.query.type === 'create'"
          >新增行</el-button
        >
      </div>
    </ContentWrap>

    <ContentWrap>
      <el-table v-loading="loading" :height="tableHeight" :data="list" border>
        <el-table-column type="index" width="55" label="序号" align="left" fixed="left"/>
        <!-- 列定义 -->
        <el-table-column label="任务单号" align="left" width="180" :class="'custom-header'">
          <template #default="scope">
            <el-select
              v-model="scope.row.taskNumber"
              placeholder="请选择任务单号"
              filterable
              remote
              :remote-method="filterOptions"
              @change="handleChange(scope.$index, scope.row.taskNumber)"
            >
              <el-option
                v-for="(dict, index) in filteredOptions"
                :key="index"
                :label="dict.taskNumber"
                :value="dict.taskNumber"
              />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="订单号" align="left" width="180">
          <template #default="scope">
            {{ scope.row.orderNumber }}
          </template>
        </el-table-column>
        <el-table-column label="客户名称" align="left" width="180" :class="'custom-header'">
          <template #default="scope">
            {{ scope.row.customerName }}
          </template>
        </el-table-column>
        <el-table-column label="订单类型" align="left" width="180" :class="'custom-header'">
          <template #default="scope">
            <dict-tag
              v-if="scope.row.dictOrderType"
              :type="DICT_TYPE.MARKET_ORDER_TYPE"
              :value="scope.row.dictOrderType"
            />
          </template>
        </el-table-column>
        <el-table-column label="产品编号" align="left" width="180" :class="'custom-header'">
          <template #default="scope">
            {{ scope.row.productNumber }}
          </template>
        </el-table-column>
        <el-table-column label="产品名称" align="left" width="180" :class="'custom-header'">
          <template #default="scope">
            {{ scope.row.productName }}
          </template>
        </el-table-column>
        <el-table-column label="产品规格" align="left" width="180" :class="'custom-header'">
          <template #default="scope">
            {{ scope.row.productStandard }}
          </template>
        </el-table-column>
        <el-table-column label="单位" align="left" width="180" :class="'custom-header'">
          <template #default="scope">
            {{scope.row.partUnit}}
            <!-- <dict-tag
              v-if="scope.row.dictUnit"
              :type="DICT_TYPE.ORDER_PRODUCT_UNIT"
              :value="scope.row.dictUnit"
            /> -->
          </template>
        </el-table-column>
        <el-table-column label="订单数量" align="left" width="180" :class="'custom-header'">
          <template #default="scope">
            {{ scope.row.orderQuantity }}
          </template>
        </el-table-column>
        <el-table-column label="订单日期" align="left" width="180" :class="'custom-header'">
          <template #default="scope">
            {{ scope.row.orderDate }}
          </template>
        </el-table-column>
        <el-table-column label="发货日期" align="left" width="180" :class="'custom-header'">
          <template #default="scope">
            {{ scope.row.deliveryDate }}
          </template>
        </el-table-column>
        <el-table-column label="任务类型" align="left" width="180" :class="'custom-header'">
          <template #default="scope">
            <dict-tag
              v-if="scope.row.dictTaskType"
              :type="DICT_TYPE.ORDER_TECHNOL_TASK_TYPE"
              :value="scope.row.dictTaskType"
            />
          </template>
        </el-table-column>
        <el-table-column label="变更类型" align="left" width="180" :class="'custom-header'">
          <template #default="scope">
            <dict-tag
              v-if="scope.row.dictChangeType"
              :type="DICT_TYPE.CHANGE_TYPE"
              :value="scope.row.dictChangeType"
            />
          </template>
        </el-table-column>
        <el-table-column label="版本号" align="left" width="180" :class="'custom-header'">
          <template #default="scope">
            {{ scope.row.version }}
          </template>
        </el-table-column>
        <el-table-column label="项目合同" align="left" width="180" :class="'custom-header'">
          <template #default="scope">
            <span style="cursor: pointer" @click="previewFile(scope.$index)">{{
              scope.row.fileName
            }}</span>
          </template>
        </el-table-column>
        <el-table-column label="技术评审表" align="left" width="180" :class="'custom-header'">
          <template #default="scope">
            <UploadFileAdd
              v-model="scope.row.fileList"
              :index="scope.$index"
              :isShowTip="false"
              :limit="1"
              :fileSize="200"
              :fileType="['pdf', 'png', 'jpg']"
              @click="uploadFile(scope.$index)"
              @update:modelValue="uploadFileRes"
            />
          </template>
        </el-table-column>
        <el-table-column label="状态" align="left" width="180" :class="'custom-header'">
          <template #default="scope">
            <dict-tag
              v-if="scope.row.dictTaskStatus"
              :type="DICT_TYPE.ORDER_TECHNOL_TASK_STATUS"
              :value="scope.row.dictTaskStatus"
            />
          </template>
        </el-table-column>
        <el-table-column label="操作" align="left" min-width="110" fixed="right">
          <template #default="scope">
            <!-- 删除按钮 -->
            <el-button
              v-if="route.query.type === 'create'"
              link
              type="danger"
              @click="deleteRow(scope.$index)"
              >删除行</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </ContentWrap>
  </div>
</template>

<script lang="ts" setup>
  import { useRoute } from 'vue-router'
  import { DICT_TYPE } from '@/utils/dict'
  import * as TechnolReviewTblApi from '@/api/orderManagement/technolReviewTbl'
  import { useTagsViewStore } from '@/store/modules/tagsView'
  const disabled = ref(false)
  const tagsViewStore = useTagsViewStore()
  const routes = useRouter() // 路由
  const route = useRoute()
  const { t } = useI18n() // 国际化
  const message = useMessage() // 消息弹窗
  const { push } = useRouter()
  const loading = ref(true)
  let title = ref('')
  const fileList = ref([])
  const changeIndex = ref(0)
  const list = ref<any>([])
  let listOption = ref<any>([])
  let filteredOptions = ref<any>([])
  //模糊查询
  const filterOptions = async (query) => {
    filteredOptions = ref<any>([])
    filteredOptions = await listOption.filter((option) => option.taskNumber.includes(query))
  }

  //获取任务单号下拉选择器选中的值
  const handleChange = async (index, value) => {
    console.log(index, value)
    for (let i = 0; i < listOption.length; i++) {
      if (listOption[i].taskNumber == value) {
        list.value[index].orderNumber = listOption[i].orderNumber
        list.value[index].customerName = listOption[i].customerName //客户简称
        list.value[index].dictOrderType = listOption[i].dictOrderType //订单类型
        list.value[index].productNumber = listOption[i].productNumber //产品编号
        list.value[index].productName = listOption[i].productName //产品名称
        list.value[index].productStandard = listOption[i].productStandard //产品规格
        list.value[index].dictUnit = listOption[i].dictUnit //单位
        list.value[index].orderQuantity = listOption[i].orderQuantity //订单数量
        list.value[index].orderDate = listOption[i].orderDate //订单日期
        list.value[index].deliveryDate = listOption[i].deliveryDate //发货日期
        list.value[index].dictTaskType = listOption[i].dictTaskType //任务类型
        list.value[index].dictChangeType = listOption[i].dictChangeType //变更类型
        list.value[index].version = listOption[i].version //版本号
        list.value[index].fileName = listOption[i].fileName //项目合同
        list.value[index].filePath = listOption[i].filePath //项目合同url
        console.log(list.value[index].fileName)
      }
    }
  }

  const addRow = () => {
    const newRow = {
      taskNumber: undefined, //任务单号
      orderNumber: undefined, //订单编号
      customerName: undefined, //客户简称
      dictOrderType: undefined, //订单类型
      productNumber: undefined, //产品编号
      productName: undefined, //产品名称
      productStandard: undefined, //产品规格
      unit: undefined, //单位
      orderQuantity: undefined, //订单数量
      orderDate: undefined, //订单日期
      deliveryDate: undefined, //发货日期
      dictTaskType: undefined, //任务类型
      dictChangeType: undefined, //变更类型
      version: undefined, //版本号
      fileName: undefined, //项目合同
      filePath: undefined, //项目合同url
      dictTaskStatus: undefined, //任务状态
      tblFilePath: undefined,
      tblFileName: undefined,
      fileList: []
    }
    list.value.push(newRow)
  }

  const deleteRow = (index: number) => {
    list.value.splice(index, 1)
  }

  //附件预览
  const previewFile = (index) => {
    list.value[index]
    window.open(list.value[index].filePath)
  }
  /**上传附件 */
  const uploadFile = (index) => {
    changeIndex.value = index
  }
  /**文件上传返回 */
  const uploadFileRes = async (data) => {
    const res = await JSON.parse(data)
    if (res.length>0) {
      let index = res[0].index
      if (JSON.parse(data).length) {
        list.value[index].tblFilePath = res[0].url
        list.value[index].tblFileName = res[0].name
      } else {
        list.value[index].tblFilePath = ''
        list.value[index].tblFileName = ''
      }
    } else {
      fileList.value = []
      list.value[changeIndex.value].tblFilePath = ''
      list.value[changeIndex.value].tblFileName = ''
    }
  }
  //必填校验
  const check = async () => {
    let data = await list.value
    for (let i = 0; i < data.length; i++) {
      if (!data[i].taskNumber) {
        message.warning(t('任务单号不能为空'))
        return false
      }
      if (!data[i].tblFilePath) {
        message.warning(t('技术评审表不能为空'))
        return false
      }
    }
    return true
  }
  /**保存 */
  const saveData = async () => {
    try {
      if (list.value.length) {
        const isFlag = await check()
        if (isFlag) {
          disabled.value = true
          let type = route.query.type
          if (type === 'create') {
            let reqData = {
              submitFlag: 1,
              createList: list.value
            }
            await TechnolReviewTblApi.createTechnolReviewTbl(reqData)
            message.success(t('common.createSuccess'))
            tagsViewStore.delView(routes.currentRoute.value)
            push('/orderManagement/orderManagement/review/reviewTbl')
            disabled.value = false
          }
        }
      } else {
        message.warning('请新增数据')
        disabled.value = false
      }
    } finally {
      disabled.value = false
    }
  }
  /**提交 */
  const submitData = async () => {
    try {
      if (list.value.length) {
        const isFlag = await check()
        if (isFlag) {
          disabled.value = true
          let type = route.query.type
          if (type === 'create') {
            let reqData = {
              submitFlag: 2,
              createList: list.value
            }
            await TechnolReviewTblApi.createTechnolReviewTbl(reqData)
            message.success(t('common.createSuccess'))
            tagsViewStore.delView(routes.currentRoute.value)
            push('/orderManagement/orderManagement/review/reviewTbl')
            disabled.value = false
          }
        }
      } else {
        message.warning('请新增数据')
        disabled.value = false
      }
    } finally {
      disabled.value = false
    }
  }
  /**关闭 */
  const close = () => {
    tagsViewStore.delView(routes.currentRoute.value)
    push('/orderManagement/orderManagement/review/reviewTbl')
  }
  //获取任务单号
  const getTaskOrderNumber = async () => {
    const data = await TechnolReviewTblApi.getTaskOrderNumber()
    console.log(data)
    listOption = data
    filteredOptions = data
    loading.value = false
  }
  // 初始化
  const tableHeight = ref(0)
  onMounted(async () => {
    tableHeight.value = document.body.clientHeight - 132 - 137
    let type = route.query.type
    if (type === 'create') {
      title.value = '新增评审任务表'
    }
    await getTaskOrderNumber()
  })
</script>
<style lang="scss" scoped>
  .btnWrap {
    display: flex;
    justify-content: space-between;
    margin-bottom: 10px;
  }
  .el-table .custom-header::before {
    content: '*';
    color: red;
    margin-right: 4px; /* 根据需要调整小红星与字段的位置 */
  }
</style>
